import com.ycz.controller.UserController;
import com.ycz.service.UserService;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @Author:ycz
 * @date:2021/6/5
 */
public class Test {

    public static void main(String[] args) throws Exception {
        UserController userController = new UserController();
        Class<? extends UserController> clazz = userController.getClass();
        // 创建对象
        UserService userService = new UserService();
        System.out.println(userService.hashCode());
        // 获取属性
        Field serviceField = clazz.getDeclaredField("userService");
        serviceField.setAccessible(true);
        // 通过方法才能设置具体的属性值
        String name = serviceField.getName();
        name = name.substring(0, 1).toUpperCase() + name.substring(1, name.length());
        String setMethodName = "set" + name;
        System.out.println("setMethodName===" + setMethodName);
        // 通过方法注入属性的对象
        Method method = clazz.getMethod(setMethodName, UserService.class);
        // 反射
        method.invoke(userController, userService);
        System.out.println(userController.getUserService());

    }

}
